package com.example.school.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.school.dto.*;
import com.example.school.pojo.Admin;
import com.example.school.service.AdminService;
import com.example.school.mapper.AdminMapper;
import com.example.school.utils.common.enums.Code;
import com.example.school.utils.common.enums.Jwt;
import com.example.school.utils.common.enums.Message;
import com.example.school.utils.common.result.PageResponseResult;
import com.example.school.utils.common.result.Result;
import com.example.school.utils.config.BaseContext;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
* @author 24354
* @description 针对表【admin】的数据库操作Service实现
* @createDate 2024-03-16 19:11:53
*/
@Service
@Slf4j
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin>
    implements AdminService{

    @Autowired
    private AdminMapper adminMapper;

    @Override
    public Result adminLogin(AdminLoginDto dto) {
        if (dto==null) {
            return Result.errorResult(Code.PARAM_REQUIRE);
        }
        Admin checkAdmin = adminMapper.selectOne(Wrappers.<Admin>lambdaQuery()
                .eq(Admin::getAdminName, dto.getAdminName())
                .or().eq(Admin::getAdminPhone, dto.getAdminName()));
        if (checkAdmin==null) {
            return Result.errorResult(Code.DATA_NOT_EXIST);
        }
        String password=checkAdmin.getAdminSalt()+dto.getPassword();
        password = DigestUtils.md5Hex(password);
        if (!checkAdmin.getAdminPassword().equals(password)) {
            return Result.errorResult(Code.LOGIN_PASSWORD_ERROR);
        }
        String id= String.valueOf(checkAdmin.getAdminId());
        String token = Jwts.builder()
                .setHeaderParam(Message.Jwt_Typ, Jwt.Admin_Jwt_Key.getTyp())
                .setHeaderParam(Message.Jwt_Alg,Jwt.Admin_Jwt_Key.getAlg())
                .setSubject(Jwt.Admin_Jwt_Key.getName())
                .setExpiration(new Date(System.currentTimeMillis()+Jwt.Admin_Jwt_Key.getExp()))
                .claim(Message.Admin_id,id)
                .signWith(SignatureAlgorithm.HS256,Jwt.Admin_Jwt_Key.getKey())
                .compact();
        return Result.okResult(token);
    }

    @Override
    public Result saveAdmin(SaveAdminDto dto) {

        if (dto==null) {
            return Result.errorResult(Code.PARAM_REQUIRE);
        }
        Long adminId = BaseContext.getCurrentId();
        Admin checkAdmin = adminMapper.selectById(adminId);
        if (adminId==null||checkAdmin==null) {
            return Result.errorResult(Code.NEED_LOGIN);
        }
        String password=checkAdmin.getAdminName()+dto.getPassword();
        password = DigestUtils.md5Hex(password);
        Admin admin=new Admin();
        admin.setAdminName(dto.getName());
        admin.setPassword(dto.getPassword());
        admin.setAdminSalt(checkAdmin.getAdminName());
        admin.setAdminPassword(password);
        admin.setAdminPhone(dto.getPhone());
        admin.setAdminNick(dto.getNick());
        log.info("admin:{}",admin);
        int checkSave = adminMapper.insert(admin);
        if (checkSave==0) {
            return Result.errorResult(Code.SERVER_ERROR);
        }

        return Result.okResult(Code.SUCCESS);
    }

    @Override
    public Result updateAdmin(AdminUpdateDto dto) {
        if (dto==null) {
            return Result.errorResult(Code.PARAM_REQUIRE);
        }
        if (BaseContext.getCurrentId()==null) {
            return Result.errorResult(Code.NEED_LOGIN);
        }
        Admin checkAdmin = adminMapper.selectById(dto.getAdminId());
        if (checkAdmin==null) {
            return Result.errorResult(Code.DATA_NOT_EXIST);
        }
        Admin admin=new Admin();
        BeanUtils.copyProperties(checkAdmin,admin);
        if (dto.getPhone()!=null) {
            admin.setAdminPhone(dto.getPhone());
        }
        if (dto.getNick()!=null&&!dto.getNick().equals("")) {
            admin.setAdminNick(dto.getNick());
        }
        if (dto.getPassword()!=null&&!dto.getPassword().equals("")) {
            String password = DigestUtils.md5Hex(checkAdmin.getAdminSalt() + dto.getPassword());
            admin.setPassword(dto.getPassword());
            admin.setAdminPassword(password);
        }
        int checkUpdate = adminMapper.updateById(admin);
        if (checkUpdate==0) {
            return Result.errorResult(Code.SERVER_ERROR);
        }
        return Result.okResult(Code.SUCCESS);
    }

    @Override
    public Result getAdminList(AdminGetListDto dto) {
        if (BaseContext.getCurrentId()==null) {
            return Result.errorResult(Code.NEED_LOGIN);
        }
        dto.checkParam();
        IPage page=new Page(dto.getPage(),dto.getSize());
        LambdaQueryWrapper<Admin> wrapper=new LambdaQueryWrapper<>();
        if (dto.getMimo()!=null) {
            wrapper.like(Admin::getAdminNick,dto.getMimo());
            wrapper.or().like(Admin::getAdminPhone,dto.getMimo());
        }
        page=page(page,wrapper);
        Result result=new PageResponseResult(dto.getPage(),dto.getSize(), (int) page.getTotal());
        result.setData(page.getRecords());
        return result;
    }
}




